<?php
	require_once('config.php');
	require_once('IXRClass.php');

  $end = time();
  $oneday = 60 * 60 * 24;
  $start = $end - $oneday * 28; // 4 weeks

  $sql = "
    select dz.id, dz.name as dz_name, count(atsk.timestamp) as cnt, 
    izp.name as izp_name, izp.id as izp_id,
    dz.spotify_id as spotify_id
    from atsk
    left join dz on atsk.dz_id = dz.id
    left join izp on dz.izp_id = izp.id
    where (pimped is null or pimped = 0 or pimped = 1)
    and atsk.timestamp > $start
    and atsk.timestamp < $end
    group by dz.id    
    having cnt > 30
    order by cnt desc
    ";

  $news1 = fetchall($sql);

  $start2 = $end - $oneday *14; // 2 weeks   
  $sql = "
    select dz.id, dz.name as dz_name, count(atsk.timestamp) as cnt, 
    izp.name as izp_name, izp.id as izp_id 
    dz.spotify_id as spotify_id
    from atsk
    left join dz on atsk.dz_id = dz.id
    left join izp on dz.izp_id = izp.id
    where (pimped is null or pimped = 0)
    and atsk.timestamp > $start2
    and atsk.timestamp < $end
    group by dz.id    
    having cnt > 10
    order by cnt desc
    ";

  $res = fetchall($sql);
  
  if (count($res) > 4) { 
    $news2 = $res;
  }
  
  $time = $end;

  if ($news1 or $news2) {
    ob_start();
    include('templates/message.php');
    $msg = ob_get_clean();
    
		$wl_client = new IXR_Client(KLAB_URL);
		$wl_client->query('LJ.XMLRPC.getchallenge');
		$challenge_data = $wl_client->getResponse();
		$magic_key = md5($challenge_data['challenge'].md5(KLAB_PASSWORD));

		$lj_data = array(
		  'username' => KLAB_USER,
		  'auth_method' => 'challenge',
		  'auth_challenge' => $challenge_data['challenge'],
		  'auth_response' => $magic_key,
		  'event' => $msg,
		  'lineendings' => 'unix',
		  'subject' => $Title,
		  'ver' => 1,
		  'year' => strftime('%Y', $time),
		  'mon' => strftime('%m', $time),
		  'day' => strftime('%d', $time),
		  'hour' => strftime('%H', $time),
		  'min' => strftime('%M', $time),
		  'security' => 'public',
		  'props' => array('opt_preformatted' => true)
		);
	
		$wl_client->query('LJ.XMLRPC.postevent', $lj_data);
		
		$resp = $wl_client->getResponse();
		
		if (array_key_exists('faultString',$resp)) {
      print_r($resp);
    } else {
      // fine, mark as pimped..
      if ($news1) {
        foreach ($news1 as $row) {
          mysql_query("update dz set pimped=2 where id = ".$row['id']);    
        }
      }
      
      if ($news2) {      
        foreach ($news2 as $row) {
          mysql_query("update dz set pimped=1 where id = ".$row['id']);    
        }
      }  
    }
  }
  
  // twitter
  function twitter_send($message, $user, $pass) {
    $url = 'https://twitter.com/statuses/update.xml';
    $post = array('status' => $message);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERPWD, $user.":".$pass);
    curl_setopt($curl, CURLOPT_HEADER, FALSE);
    curl_setopt($curl, CURLOPT_TIMEOUT, 20);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));

    if ($post) {
      curl_setopt($curl, CURLOPT_POST, TRUE);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // no echo, just return result
    $result = curl_exec($curl);
    $ok = curl_errno($curl) === 0 && curl_getinfo($curl, CURLINFO_HTTP_CODE) === 200;
    return $result;
  }  
  
  if ($news1) {
    foreach ($news1 as $row) {
        $izp = utf8_encode($row['izp_name']);
        $dz = utf8_encode($row['dz_name']);
        $status = $izp.' - '.$dz.' pēdējā mēnesī spēlēta vairāk kā 30 reizes';
        if ($row['spotify_id']) {
            $link = make_spotify_http_link($row['spotify_id']);
            $tiny = get_tinyurl($link);
            if (count($status.$tiny) < 139) {
                $status .= ' '.$tiny;
            }
        }
        twitter_send($status, TWITTER_USER, TWITTER_PASSWORD);  
    }
  }

?>
